package com.bailiny.basicUtils;


import java.util.Collections;
import java.util.List;

import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Test;

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;

/**
 * 流畅风格比较器 </br>
 * 排序器[Ordering]是Guava流畅风格比较器[Comparator]的实现，它可以用来为构建复杂的比较器，以完成集合排序的功能。
 */
public class OrderingDemo {

	@Test
	public void test() {
		Ordering<String> byLengthOrdering = new Ordering<String>() {
			@Override
			public int compare(@Nullable String left, @Nullable String right) {
				return Ints.compare(left.length(), right.length());
			}
		};
		List<String> list = Lists.newArrayList("fsd", "fdsfds", "df");
		Collections.sort(list, byLengthOrdering);
		list.forEach(s -> {
			System.out.println(s);
		});
	}
	
	@Test
    public void testOrdering(){
 
        List<String> stringList = Lists.newArrayList("b","a","h","z","d","e","3","1","k","a","9","m","k");
        System.out.println(Ordering.natural().max(stringList)); // z
        System.out.println(Ordering.natural().min(stringList)); // 1
 
        System.out.println("====================================================");
 
        List<String> stringList1 = Lists.newArrayList("b","a","h","z","d","e","3","1",null,"k","a","9","m","k");
        System.out.println(stringList1);
        List<String> stringList2 = Ordering.natural().nullsFirst().sortedCopy(stringList1);
        System.out.println("自然排序：" + stringList2);
 
        List<String> stringList3 = Ordering.usingToString().nullsFirst().sortedCopy(stringList1);
        System.out.println("字符串排序：" + stringList3);
 
        System.out.println("====================================================");
 
        List<String> stringList4 = Lists.newArrayList("ba","addd","hdd","z","d2243","e5","3325235","1262",null,"k3","a1","9","m3","k333");
        System.out.println(stringList4);
        Ordering<String> ordering = new Ordering<String>() {
            @Override
            public int compare(String left, String right) {
                return Ints.compare(left.length(),right.length());
            }
        };
        List<String> stringList5 = ordering.nullsFirst().reverse().sortedCopy(stringList4);
        System.out.println("自定义排序：" + stringList5);
        System.out.println("是否是有序的？：" + ordering.nullsFirst().reverse().isOrdered(stringList5));
        // 取出最大和最小的的3个
        List<String> stringList6 = ordering.nullsFirst().reverse().greatestOf(stringList4, 3);
        List<String> stringList7 = ordering.nullsFirst().reverse().leastOf(stringList4, 3);
        System.out.println(stringList6);
        System.out.println(stringList7);
 
    }
}
